import { createRouter, createWebHistory } from "vue-router";

import Home from '../components/home/Home.vue';
// 
	import Main from '../components/home/page/Main.vue';
// 
	import Detail from '../components/home/page/Detail.vue';
// 
	import Cart from '../components/home/page/Cart.vue';
//
	import Myorder from '../components/home/page/Myorder.vue';
//
	import Personal from '../components/home/page/Personal.vue';
//
// 

import Admin from '../components/admin/Admin.vue';
// 
	import Type from '../components/admin/page/Type.vue';
// 
	import Type2 from '../components/admin/page/Type2.vue';
// 
	import TypeAdd from '../components/admin/page/TypeAdd.vue';
// 
	import TypeEdit from '../components/admin/page/TypeEdit.vue';
	
	import Banner from '../components/admin/page/Banner.vue';
	
	import Book from '../components/admin/page/Book.vue';

const routes = [
	{
		path:'/',
		// redirect:{
		// 	name:'Home',
		// },
		redirect:'/home',
	},
	{
		path:'/home',
		name:'Home',
		component:Home,
		children:[
			{
				path:'',
				name:'Main',
				component:Main,
			},
			{
				path:'details',
				name:'Detail',
				component:Detail,
			},
			{
				path:'cart',
				name:'Cart',
				component:Cart,
				meta:{
					role:'P',
				}
			},
			{
				path:'myorder',
				name:'Myorder',
				component:Myorder,
				meta:{
					role:'P',
				}
			},
			{
				path:'personal',
				name:'Personal',
				component:Personal,
				meta:{
					role:'P',
				}
			}
		]
	},
	{
		path:'/admin',
		name:'Admin',
		component:Admin,
		children:[
			{
				path:'type',
				name:'Type',
				component:Type,
			},
			{
				path:'type2',
				name:'Type2',
				component:Type2,
			},
			{
				path:'typeAdd',
				name:'TypeAdd',
				component:TypeAdd,
			},
			{
				path:'typeEdit',
				name:'TypeEdit',
				component:TypeEdit,
			},
			{
				path:'banner',
				name:'Banner',
				component:Banner,
			},
			{
				path:'book',
				name:'Book',
				component:Book,
			}
		]
	}
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 路由守卫：在跳转下一个页面之前，判断当前用户是否合法/是否具有访问权限
router.beforeEach( (to , from , next)=>{
	// 1.在任意一个地址跳转的时候，从本地存储中获取当前登录的角色值【未登录，role为空】
	let role = localStorage.getItem('role');
	// 没有限制规则的路径地址也能正常访问
	if( to.meta.role == undefined || to.meta.role == '' ){
		next();
		return;
	}
	
	// 进入后台首页：role 是否与规划中的要求匹配
	// 判断即将进入的路由规则中限制的访问角色规则 是否与当前登录的角色匹配
	if( to.meta.role == role ){
		// 继续进入
		next();
		return;
	}
	// 以上都不需要的路由，默认跳转返回登录页
	router.replace('/home').catch( (error)=>{
		console.log('地址不存在');
	})
})

export default router;
